﻿using Hangfire;
using Hangfire.Annotations;
using Hangfire.MemoryStorage;
using Hangfire.Server;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;

namespace Helpers
{
    public static class HangfireExtensions
    {
        /// <summary>
        /// 启动内存定时器
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IServiceCollection AddHangfirez(this IServiceCollection services, HangfireHelperOptions options)
        {
            services.AddHangfire(x => x.UseMemoryStorage());
            if (options.StartHangfireServer)
            {
                services.AddHangfireServer(x => options.SetupHangfireServer?.Invoke(x));
            }
            services.AddSingleton<HangfireHelperOptions>((x) => options);
            services.AddSingleton<IStartupFilter, StartHangfireServerStartupFilter>();
            return services;
        }

        /// <summary>
        /// 默认添加MemoryStorage
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddHangfirez(this IServiceCollection services)
        {
            services.AddHangfire(x => x.UseMemoryStorage());
            return services;
        }

        /// <summary>
        /// 控制台需要添加这个注入IBackgroundJobClient和IRecurringJobManager
        /// </summary>
        public static IServiceCollection AddHangfireServerz(this IServiceCollection services, Action<BackgroundJobServerOptions> optionsAction = null)
        {
            services.AddHangfireServer(options =>
            {
                optionsAction?.Invoke(options);
            });
            return services;
        }

        public static IApplicationBuilder UseHangfireServerz([NotNull] this IApplicationBuilder app, [CanBeNull] BackgroundJobServerOptions options = null, [CanBeNull] IEnumerable<IBackgroundProcess> additionalProcesses = null, [CanBeNull] JobStorage storage = null)
        {
            app.UseHangfireServer(options, additionalProcesses, storage);
            return app;
        }

        public static IApplicationBuilder UseHangfireDashboardz([NotNull] this IApplicationBuilder app, [NotNull] string pathMatch = "/hangfire", [CanBeNull] DashboardOptions options = null, [CanBeNull] JobStorage storage = null)
        {
            app.UseHangfireDashboard(pathMatch, options, storage);
            return app;
        }
    }
}
